/**
 * 
 */

package com.shy.portal.dao.impl;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.shy.base.dao.impl.BaseDaoImpl;
import com.shy.base.vo.EntityTypeValue;
import com.shy.base.vo.PagerFilter;
import com.shy.base.vo.QueryResult;
import com.shy.portal.dao.MenuDao;
import com.shy.portal.entity.Menu;

/**
 * <p>
 * Title: MenuDaoImpl
 * </p>
 * <p>
 * Description:菜单管理dao层实现
 * </p>
 * <p>
 * Company:ipebg
 * </p>
 * 
 * @author H2013788
 */
@Repository("menuDao")
public class MenuDaoImpl extends BaseDaoImpl<Menu> implements MenuDao {

    /**
     * 返回listMenuByPager
     */
    @Override
    public PagerFilter listMenuByPager(String whereHql, List<EntityTypeValue> params,
            PagerFilter pagerFilter) {
        Integer firstStart = Integer.parseInt(String.valueOf(pagerFilter.getStart())); // 分页开始下标
        Integer showNum = Integer.parseInt(String.valueOf(pagerFilter.getMax())); // 显示条数
        QueryResult<Menu> result = this.getScrollDataBindName(firstStart, showNum, whereHql,//暫定查询200條数据
                params, pagerFilter.getOrderby());
        if (result != null) {
            pagerFilter.setTotal(result.getTotalrecord());
            pagerFilter.setObjs(result.getResultlist());
        }
        return pagerFilter;
    }

    @Override
    public int getMaxLevel() {
        String sql = "select Max(level) from Menu ";
        Query query = entityManager.createQuery(sql);
        Object o = query.getSingleResult();
        if (o != null && !"".equals(o.toString())) {
            return Integer.parseInt(o.toString());
        }
        return 0;
    }

    @Override
    public int getMaxSortByParent(Integer pid) {
        String sql = " select Max(sort) from Menu ";
        if (null != pid) {
            sql += " where parent_id =:pid ";
        } else {
            sql += " where level = 1 ";
        }
        Query query = entityManager.createQuery(sql);
        if (null != pid) {
            query.setParameter("pid", pid);
        }
        Object o = query.getSingleResult();;
        return o == null ? 0 : Integer.parseInt(o.toString());
    }

    @SuppressWarnings("unchecked")
	@Override
    public List<Menu> findAllListOrderByCode() {
        String hql = "from Menu o order by o.menuCode asc ";
        Query query = entityManager.createQuery(hql);
        return query.getResultList();
    }

    @SuppressWarnings("unchecked")
	@Override
    public List<Menu> getMenusByRoleId(Integer roleId) {
        String hql = " FROM Menu WHERE id IN ( SELECT DISTINCT menu.id FROM RoleMenu WHERE role.id =:roleId ) ORDER BY sort ASC ";
        Query query = entityManager.createQuery(hql);
        query.setParameter("roleId", roleId);
        List<Menu> list = query.getResultList();
        return list;
    }

}
